<template>
  <div class="htx-code">
    <div class="l-container">
      <el-row>
        <div class="code-top">
          <Select @modeChange="handleModeChange" />
          <div class="btn-list">
            <el-button type="primary" plain @click="handleCodeFormat">格式化</el-button>
            <el-button type="primary" plain @click="handleCodeMin">压缩</el-button>
          </div>
        </div>
      </el-row>
      <el-row>
        <div class="code-edit">
          <codemirror v-model="code" :options="cmOptions" ref="editor" />
        </div>
      </el-row>
    </div>
  </div>
</template>

<script>
import { codemirror } from 'vue-codemirror';
import beautify from 'js-beautify';
import htmlMinify from '@/lib/minify';

import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/css/css';
import 'codemirror/mode/htmlmixed/htmlmixed';

import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';

import Select from './components/Select.vue';

export default {
  data() {
    return {
      code: '',
      cmOptions: {
        tabSize: 2,
        mode: 'text/javascript',
        theme: 'material',
        lineNumbers: true,
        line: true,
      },
      currentMode: 'text/javascript', // 当前代码语言
      beautifyFun: beautify.js, // 默认格式化js
      // 格式化设置
      beautifyOption: {
        indent_size: '2',
        indent_char: ' ',
        max_preserve_newlines: '2',
        preserve_newlines: true,
        keep_array_indentation: false,
        break_chained_methods: false,
        indent_scripts: 'normal',
        brace_style: 'collapse',
        space_before_conditional: false,
        unescape_strings: false,
        jslint_happy: false,
        end_with_newline: false,
        wrap_line_length: '110',
        indent_inner_html: false,
        comma_first: false,
        e4x: false,
        indent_empty_lines: false,
      },
    };
  },
  components: { codemirror, Select },
  computed: {
    // 编辑器实例
    codeMirror() {
      return this.$refs.editor.codemirror;
    },
  },
  watch: {
    currentMode(nV) {
      if (nV === 'text/javascript') {
        this.beautifyFun = beautify.js;
      } else if (nV === 'text/css') {
        this.beautifyFun = beautify.css;
      } else {
        this.beautifyFun = beautify.html;
      }
      this.cmOptions.mode = nV;
    },
  },
  methods: {
    // 代码格式化
    handleCodeFormat() {
      try {
        this.code = this.beautifyFun(this.code, this.beautifyOption);
      } catch (e) {
        this.$notify.error({
          title: '格式化错误',
          message: '请重新输入',
        });
      }
    },
    // 代码压缩
    handleCodeMin() {
      try {
        this.code = htmlMinify(this.code);
      } catch (e) {
        this.$notify.error({
          title: '压缩错误',
          message: '请重新输入',
        });
      }
    },
    // 代码语言修改
    handleModeChange(modeType) {
      this.currentMode = modeType;
    },
  },
};
</script>
